import requests
import json
import logging
logger = logging.getLogger('django')

from django.conf import settings

class SMS(object):
    def __init__(self,sms_phone,sms_content):

        # 创蓝API账号
        self.account = settings.CL_FYX_ACCOUNT
        # 创蓝API密码
        self.password = settings.CL_FYX_PSW


        # 余额查询的URL
        self.balance_get_uri = "/msg/balance/json"
        # 普通短信发送的URL
        self.sms_send_uri = "https://smssh1.253.com/msg/v1/send/json"
        self.headers ={"Content-type": "application/json;charset=utf-8"}
        #发送短信的手机号
        self.sms_phone =sms_phone
        #自定义短信发送的内容
        self.sms_content =sms_content


    def get_user_balance(self):
        '''
        取账户余额
        :return: 返回短余额结果
        '''
        params = {'account': self.account, 'password': self.password}
        try:

            response = requests.post(url=self.host+self.balance_get_uri,params=json.dumps(params),headers=self.headers)
            if response.status_code == 200:
                return response.json()
        except BaseException as e:
            logger.error('获取短信余额接口异常：%s'%e)

    def send_sms(self):
        '''
        发送短信
        :return: 发送短信结果
        '''

        params = {
            "account": self.account,
            "password": self.password,
            "msg": self.sms_content,
            "phone": self.sms_phone

        }
        try:

            response = requests.post(url=self.sms_send_uri, json=params,
                                     headers=self.headers)
            if response.status_code == 200:
                if response.json().get('code') == '0':
                    return '短信发送成功'
                else:
                    return f"短信发送失败: {response.json().get('errorMsg', '未知错误')}"
            else:
                return '短信接口返回状态不对'

        except BaseException as e:
            logger.error('获取发送短信接口异常：%s' % e)
            return '短信发送异常'
